package org.duanyu.shopping_pay_service.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import org.apache.dubbo.config.annotation.DubboService;
import org.duanyu.shopping_common.pojo.Orders;
import org.duanyu.shopping_common.pojo.Payment;
import org.duanyu.shopping_common.result.BusException;
import org.duanyu.shopping_common.result.CodeEnum;
import org.duanyu.shopping_common.service.ZfbPayService;
import org.duanyu.shopping_pay_service.ZfbPayConfig;
import org.duanyu.shopping_pay_service.mapper.PaymentMapper;
import org.duanyu.shopping_pay_service.util.ZfbVerifierUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@DubboService
@Transactional
public class ZfbPayServiceImpl implements ZfbPayService {

    @Autowired
    private ZfbPayConfig zfbPayConfig;

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private PaymentMapper paymentMapper;

    @Override
    public String pcPay(Orders orders) {

        /*
        * 判断订单状态，只有未支付的订单才会生成二维码
        * */
        if (orders.getStatus()!=1){
            throw new BusException(CodeEnum.ORDER_STATS_ERROR);
        }
        //1.创建请求对象
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        //2.设置请求
        request.setNotifyUrl(zfbPayConfig.getNotifyUrl() + zfbPayConfig.getPcNotify());
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orders.getId());
        bizContent.put("total_amount", orders.getPayment());
        bizContent.put("subject", orders.getCartGoods().get(0).getGoodsName());  //订单标题
        request.setBizContent(bizContent.toString());

        try {
            //3.发送请求
            AlipayTradePrecreateResponse response = alipayClient.execute(request);
            //4.返回二维码
            return response.getQrCode();
        } catch (AlipayApiException e) {
            throw new BusException(CodeEnum.QR_CODE_ERROR);
        }
    }

    @Override
    public void checkSign(Map<String, Object> paramMap) {
        //获取所有参数
        Map<String,String[]> requestParameterMap = (Map<String, String[]>) paramMap.get("requestParameterMap");
        //验签
        boolean valid = ZfbVerifierUtils.isValid(requestParameterMap, zfbPayConfig.getPublicKey());
        //验签失败，抛出异常
        if (!valid){
            throw new BusException(CodeEnum.CHEKC_SIGN_ERROR);
        }

    }

    @Override
    public void addPayment(Payment payment) {
        paymentMapper.insert(payment);
    }
}
